//
//  LDSearchBar.m
//  Gift
//
//  Created by 李迪 on 15/11/20.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "LDSearchBar.h"
#import "BaseHeader.h"
#import "LDSearchCell.h"

@interface LDSearchBar ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, retain)UITableView *tab;
@property (nonatomic, retain)UISearchBar *searchBar;
@property (nonatomic, retain)NSString *str;
@property (nonatomic, retain)NSMutableArray *array;

@end

@implementation LDSearchBar

-(void)dealloc{
    self.tab.delegate = nil;
    self.tab.dataSource = nil;
    [self.tab release];
    [self.searchBar release];
    [self.str release];
    [super dealloc];
}


- (void)craeteTab{
    
    self.tab = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.tab registerClass:[LDSearchCell class] forCellReuseIdentifier:@"SearchCell"];
    self.tab.rowHeight = SCREEN_HEIGHT / 3;
    self.tab.delegate = self;
    self.tab.dataSource = self;
    self.tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tab];
    

    
}

- (void)craeteSearchBar{
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    _searchBar.placeholder = @"请输入要搜索的内容";
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor whiteColor];
    _searchBar.searchBarStyle = UISearchBarStyleProminent;
    [self.view addSubview:_searchBar];
    
    [self craeteTab];
}






-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [_searchBar resignFirstResponder];
    _str = [NSMutableString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=", self.searchBar.text].mutableCopy;
    
    [self afndatanumber];
    //移除上一次请求的数据
    [self.array removeAllObjects];
    
    [self craeteTab];
    
}

#pragma mark - 网络数据请求
- (void)afndatanumber
{
    [PFAFNetworking getUrl:self.str body:nil response:PFJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        for (NSDictionary *dic in [[resposeObject objectForKey:@"data"]objectForKey:@"items"]) {
            GiftModel *model = [GiftModel modelWithDic:dic];
            [self.array addObject:model];
         
        }
        [self.tab reloadData];
        if (self.array.count == 0) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Error: 没有找到想要的礼物\nQAQ" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
            [alert addAction:defaultAction];
            
            
            UIAlertAction* action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
      
    }];
 

}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.array.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        LDSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
    
    GiftModel *model = [self.array objectAtIndex:indexPath.row];
    cell.model = model;
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:model.name];
    NSRange range = [model.name rangeOfString:self.searchBar.text];
    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.title.attributedText = attString;
    [attString release];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [[NSMutableArray array] init];
    [self craeteSearchBar];
    }


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
